﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Collections;
using System.Reflection;
using System.Text.RegularExpressions;
using WAU.Common;
using WAU.Common.Attributes;
using WAU.Common.Middlewares;

namespace WAU.Controllers
{
    /// <summary>
    /// 用于查看和设置系统状态的控制器
    /// </summary>
    [ApiController]
    [Route("[controller]/[action]")]
    public class ManageSystemController : ControllerBase
    {

#pragma warning disable CS8602 // 解引用可能出现空引用。
#pragma warning disable CS8605 // 取消装箱可能为 null 的值。

        /// <summary>
        /// 获取 组件MemoryCache 中所有的键值对
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetAllMemoryCacheForComponent()
        {
            const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
            IMemoryCache memoryCache = MemoryCacheForComponent.MemoryCache;
            var entries = memoryCache.GetType().GetField("_entries", flags).GetValue(memoryCache);

            List<string> keys = new List<string>();

            if (entries is IDictionary cacheItems) 
            {
                foreach (DictionaryEntry cacheItem in cacheItems)
                {
                    keys.Add(cacheItem.Key.ToString() + "-" + ((ICacheEntry)cacheItem.Value).Value);
                }
            }

            return new OkObjectResult(keys);
        }

        /// <summary>
        /// 重置 组件MemoryCache 中所有节流器相关的的缓存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ResetAllThrottleMemoryCache()
        {
            const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
            IMemoryCache memoryCache = MemoryCacheForComponent.MemoryCache;
            var entries = memoryCache.GetType().GetField("_entries", flags).GetValue(memoryCache);

            string[] targetTags = new string[] 
            { 
                ActionThrottleAttribute.CACHE_TAG, 
                RequestThrottleMiddleaware.CACHE_TAG,
                AntiRepeatedCommitAttribute.CACHE_TAG
            };
            Regex tagRegex = new Regex("[" + string.Join("|", targetTags) + "]");

            if (entries is IDictionary cacheItems)
            {
                foreach (DictionaryEntry cacheItem in cacheItems)
                {
                    if (tagRegex.IsMatch(cacheItem.Key.ToString()))
                    {
                        cacheItems.Remove(cacheItem.Key);
                    }
                }
            }

            return Ok(true);
        }

#pragma warning restore CS8602 // 解引用可能出现空引用
#pragma warning restore CS8605 // 取消装箱可能为 null 的值。

    }
}
